package com.i8office.android.zhihuixinwu.ui.dep;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.cyan.tools.util.RxBus;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.bean.TabItem;
import com.i8office.android.zhihuixinwu.bean.WorkSheetNew;
import com.i8office.android.zhihuixinwu.module.contract.ModifyOpinionContract;
import com.i8office.android.zhihuixinwu.module.presenter.ModifyOpinionPresenter;
import com.i8office.android.zhihuixinwu.ui.OpinionFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.Main;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import tools.ToastUtil;

@ActivityFragmentInject(
        contentViewId = R.layout.activity_modify_suggestion,
        toolbarTitle = R.string.modify_sign_suggestion
)
public class ModifySuggestionDepActivity extends BaseActivity<ModifyOpinionContract.Presenter> implements ModifyOpinionContract.View {
    @BindView(R.id.opinion)
    EditText opinion;
    @BindView(R.id.tabLayout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.submit)
    View submit;

    String titles[] = {"常用意见模板", "个人意见模板"};
    Observable<String> observable;
    Disposable disposable;

    WorkSheetNew workSheet;
    List<OpinionFragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        workSheet = (WorkSheetNew) getIntent().getSerializableExtra("workSheet");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        OpinionFragment fragment1 = new OpinionFragment();
        Bundle bundle1 = new Bundle();
        fragment1.setArguments(bundle1);
        fragments.add(fragment1);

        OpinionFragment fragment2 = new OpinionFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putBoolean("is_private", true);
        fragment2.setArguments(bundle2);
        fragments.add(fragment2);

        initViewPager();
        mPresenter = new ModifyOpinionPresenter(this);
        observable = RxBus.get().register("add_opinion", String.class);
        disposable = observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                opinion.setText(s);
                opinion.setSelection(s.length());
            }
        });
//        opinion.setText(workSheet.getModify().getOldOpinion());
//        opinion.setSelection(workSheet.getModify().getOldOpinion().length());
    }



    //获取Tab
    private void initViewPager() {
        tabLayout.setTabData(titles);
        tabLayout.setVisibility(View.VISIBLE);
        ArrayList<TabItem> tabItems = new ArrayList<TabItem>();
        tabItems.add(new TabItem("1"));
        tabItems.add(new TabItem("2"));
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }
        });
        setupWithViewPager();
    }

    private void setupWithViewPager() {
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }
    private void showDialogProgress(){
        if (progressDialog == null){
            progressDialog = ProgressDialog.show(this, "", "正在提交");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        else
            progressDialog.show();
    }
    private void hideDialogProgress(){
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }
    @OnClick(R.id.submit)
    public void onViewClicked() {
        showDialogProgress();
        submit.setEnabled(false);
        String opinionStr = opinion.getText().toString().trim();
        if (TextUtils.isEmpty(opinionStr)) {
            ToastUtil.show(this, R.string.input_option_error);
            return;
        }
        Map<String, String> params = new HashMap<>();
//        params.put("mid", workSheet.getMid());
//        params.put("nid", workSheet.getNid());
//        params.put("order", workSheet.getModify().getOrder());
        params.put("opinion", opinionStr);
        mPresenter.modify(params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) {
            RxBus.get().unregister("add_opinion", observable);

        }
    }

    @Override
    public void modifySuccess() {
        hideDialogProgress();
        RxBus.get().post("submitSuccess", "");
        toast(R.string.submit_success);
        if (DetailDepActivity.from.equals("office")) {
            Intent intent = new Intent(this, OfficeNewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (DetailDepActivity.from.equals("main")) {
            Intent intent = new Intent(this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        DetailDepActivity.from = "";
    }

    @Override
    public void modifyFailed() {
        hideDialogProgress();
        submit.setEnabled(true);
    }
}
